const int LIGHT_MAX = 4;
struct light
{
	int type;
	vec3 light;//光源坐标
	float intensity;//光强
};
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform vec3 inSpecularCoefficient;
uniform vec3 inAmbientCoefficient;
uniform light inLight[LIGHT_MAX];
varying vec2 outTexCoord;
varying mat3 outTBN;
varying vec3 outLightDir[LIGHT_MAX];
varying vec3 outHalf[LIGHT_MAX];
varying float outDis[LIGHT_MAX];

vec3 getDiffuse(vec3 normal, vec3 l, float dis, float intensity)
{
	vec3 diffuse = vec3(texture2D(tex0,outTexCoord))*(intensity/(dis*dis)*max(0,dot(normal,l)));
	return diffuse;
}

vec3 getSpecular(vec3 normal, vec3 h, float dis, float intensity)
{
	vec3 specular = inSpecularCoefficient*(intensity/(dis*dis)*pow(max(0,dot(normal,h)),128));
	return specular;
}

void main()
{
	vec3 color = vec3(0.0);
	vec3 normal = vec3(texture2D(tex1,outTexCoord));
	normal = normalize(normal * 2.0 - 1.0);
	normal = normalize(outTBN * normal);
	for (int i=0; i<LIGHT_MAX; ++i)
	{
		if(inLight[i].type>0)
		{
			color += inAmbientCoefficient+getDiffuse(normal,outLightDir[i],outDis[i],inLight[i].intensity)+getSpecular(normal,outHalf[i],outDis[i],inLight[i].intensity);
		}
	}
	gl_FragColor=vec4(color, 1.0);
}